package com.ruoyi.service.app;

import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.app.AppUserLoginDB;
import com.ruoyi.common.exception.global.CustomException;
import com.ruoyi.system.mapper.app.AppUserLoginMapper;
import com.ruoyi.util.jwt.SecurityUtils;
import com.ruoyi.util.jwt.UserRequestBaseInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class AppCommonService {
    @Resource
    private AppUserLoginMapper appUserLoginMapper;

    // 获取登录用户

    // 获取该登录用户是否存在
    public boolean checkUserExistsByMiniOpenId(String openId) {
        UserRequestBaseInfo requestHead = SecurityUtils.getRequestHead();
        if (ObjectUtils.isEmpty(requestHead)) {
            throw new RuntimeException("用户信息有误");
        }

        openId = ObjectUtils.isEmpty(openId) ? requestHead.getOpenId() : openId;
        if (ObjectUtils.isEmpty(openId) && ObjectUtils.isEmpty(requestHead.getOpenId())) {
            throw new CustomException("请先登录", HttpStatus.HTTP_UNAUTHORIZED);
        }


        if (ObjectUtils.isEmpty(requestHead.getTenantId())) {
            throw new CustomException("租户id不存在");
        }


        LambdaQueryWrapper<AppUserLoginDB> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppUserLoginDB::getMiniOpenid, openId);

        return appUserLoginMapper.exists(queryWrapper);
    }

    public AppUserLoginDB getUserByMiniOpenId(String openId) {
        UserRequestBaseInfo requestHead = SecurityUtils.getRequestHead();
        if (ObjectUtils.isEmpty(requestHead)) {
            throw new RuntimeException("用户信息有误");
        }
        if (ObjectUtils.isEmpty(openId) && ObjectUtils.isEmpty(requestHead.getOpenId())) {
            throw new CustomException("请先登录", HttpStatus.HTTP_UNAUTHORIZED);
        }
        openId = ObjectUtils.isEmpty(openId) ? requestHead.getOpenId() : openId;
        if (ObjectUtils.isEmpty(requestHead.getTenantId())) {
            throw new CustomException("租户id不存在");
        }
        LambdaQueryWrapper<AppUserLoginDB> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppUserLoginDB::getMiniOpenid, openId);
        return appUserLoginMapper.selectOne(queryWrapper);
    }


}
